package com.example.demoex3.controller;

import com.example.demoex3.model.*;
import com.example.demoex3.services.DataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class VirusController {

    @Autowired
    private DataService dataService;

    //输出所有国家
    @RequestMapping("/")
    public String getAllRegionStats(HttpServletRequest request, HttpServletResponse response, org.springframework.ui.Model model) throws ServletException, IOException {
        List<Model> models = dataService.getAllRegionStats();
        Date nowTime = new Date();
        Integer latestTotalCases;
        Integer diffFromPrevDay;
        latestTotalCases = models.stream().mapToInt(Model::getLatestTotalCases).sum();
        diffFromPrevDay = models.stream().mapToInt(Model::getDiffFromPrevDay).sum();
        model.addAttribute("customer",models);
        model.addAttribute("date",nowTime);
        model.addAttribute("sum",latestTotalCases);
        model.addAttribute("increase",diffFromPrevDay);
        return "index";
    }

    //输出查询国家或地区
    @RequestMapping("/{cty}")
    public String getByCountry(org.springframework.ui.Model model, @PathVariable("cty") String country) {

        List<Model> models;
        if(country==null||country.equals("all")){
            models = dataService.getAllRegionStats();
        }else {

            models = dataService.getAllRegionStats()
                    .parallelStream()
                    .filter(locationStats->locationStats.getCountry().equals(country))
                    .collect(Collectors.toUnmodifiableList());
        }
        Date nowTime = new Date();
        Integer latestTotalCases;
        Integer diffFromPrevDay;
        latestTotalCases =models.stream().mapToInt(Model::getLatestTotalCases).sum();
        diffFromPrevDay =models.stream().mapToInt(Model::getDiffFromPrevDay).sum();

        //让前端读到数据
        model.addAttribute("customer",models);
        model.addAttribute("date",nowTime);
        model.addAttribute("sum",latestTotalCases);
        model.addAttribute("increase",diffFromPrevDay);
        model.addAttribute("country",country);

        return "index";
    }
}
